
/*
 * atmega_adc.c
 *
 * Created: 4/4/2011 17:03:26
 *  Author: morpheus
 */ 

#include "atmega_adc.h"


void initADC() 
{ 
  // adc referance voltage
  ADMUX |= (1 << REFS0); 

  // For Aref=AVcc; 
  
  //Rrescalar div factor =128
  ADCSRA = (1 << ADEN) | (1 << ADPS2) | (1 << ADPS1) | (1<<ADPS0); 
  
	ADCSRA = (1 << ADEN) | (1 << ADPS2) | (1 << ADPS1);
  // Free running
  //ADCSRA |= (1 << ADATE);

  // Left adjust ADC result to allow easy 8 bit reading  
  //ADMUX |= (1 << ADLAR);
} 

uint16_t readADC(uint8_t ch) 
{ 

  // Select ADC Channel ch must be 0-7, in case some 
  // other components will be added to the system that require ADC 

  ADMUX &= 0b11100000; 
  ADMUX |= ch; 

  //Start Single conversion 
  ADCSRA |= (1 << ADSC); 

  //Wait for conversion to complete 

  while(!bit_is_set(ADCSRA, ADIF)); 

  //Clear ADIF by writing one to it 
  ADCSRA |= (1<<ADIF); 

  return(ADC); 
} 
/************************************************************************/
/* Loop Twice to see if that will allow a multi channel read
/************************************************************************/
uint16_t ReadADC(uint8_t __channel)
{
	// mux channels should be cleared before opp
	ADMUX &= 0b11100000; // clear bottom 4 bits 
   ADMUX |= __channel;                // Channel selection
   /*
   ADCSRA |= _BV(ADSC);               // Start conversion
   while(!bit_is_set(ADCSRA,ADIF));   // Loop until conversion is complete
   ADCSRA |= _BV(ADIF);               // Clear ADIF by writing a 1 (this sets the value to 0)
*/
	ADCSRA |= _BV(ADSC);               // Start conversion
   while(!bit_is_set(ADCSRA,ADIF));   // Loop until conversion is complete
   ADCSRA |= _BV(ADIF);               // Clear ADIF by writing a 1 (this sets the value to 0)
   
   return(ADC);
}


